// See https://aka.ms/new-console-template for more information
using System.Data;
using System.IO.Ports;
using System.Text;
using Sensor.SerialPorts;
using Sensor.SerialPorts.Enums;

Console.ReadLine();
SerialPortHandler serialPortHandler = new();

try
{
    serialPortHandler.Open("COM5", 115200, ParityBit.None, StopBit.One, 8);
    while (true)
    {
        Console.ReadLine();
        // 3. 生成单帧数据
        string frameData = GenerateFrameData();

        // 4. 发送单帧数据
        serialPortHandler.Send(Encoding.UTF8.GetBytes(frameData));

        await Task.Delay(0);
        Console.WriteLine($"发送成功:{frameData}");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"错误：{ex.Message}");
}
finally
{
    // 5. 释放资源
    serialPortHandler?.Close();
    serialPortHandler?.Dispose();
    Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
    Console.WriteLine("程序已退出");
}


/// <summary>
/// 生成单帧数据（格式：d0 x0 y0 z0 d1 x1 y1 z1 d2 x2 y2 z2 d3 x3 y3 z3 \r\n）
/// </summary>
static string GenerateFrameData()
{
    var random = new Random();
    
    // 生成X/Y坐标：范围-10到10
    double x0 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double y0 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double z0 = Math.Round(random.NextDouble() * 25, 2); // Z坐标：范围0到25
    
    double x1 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double y1 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double z1 = Math.Round(random.NextDouble() * 25, 2);
    
    double x2 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double y2 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double z2 = Math.Round(random.NextDouble() * 25, 2);
    
    double x3 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double y3 = Math.Round(random.NextDouble() * 20 - 10, 2);
    double z3 = Math.Round(random.NextDouble() * 25, 2);
    
    return $"d0 {x0} {y0} {z0} " +
           $"d1 {x1} {y1} {z1} " +
           $"d2 {x2} {y2} {z2} " +
           $"d3 {x3} {y3} {z3}\r\n";
}